package com.example.activitysys.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.example.activitysys.entity.ClaimRecord;
import com.example.activitysys.entity.LostItem;
import com.example.activitysys.service.ClaimRecordService;
import com.example.activitysys.service.LostItemService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpSession;
import java.time.LocalDateTime;

@Controller
@RequestMapping("/claim-record")
public class ClaimRecordController {

    @Autowired
    private ClaimRecordService claimRecordService;

    @Autowired
    private LostItemService lostItemService;

    /**
     * 认领记录列表页面
     */
    @GetMapping("/list")
    public String list(@RequestParam(defaultValue = "1") Integer page,
                       @RequestParam(defaultValue = "10") Integer size,
                       @RequestParam(required = false) String claimer,
                       Model model, HttpSession session) {
        
        // 检查登录状态
        if (session.getAttribute("admin") == null) {
            return "redirect:/login";
        }

        // 构建查询条件
        QueryWrapper<ClaimRecord> wrapper = new QueryWrapper<>();
        wrapper.orderByDesc("claim_time");
        
        if (StringUtils.hasText(claimer)) {
            wrapper.like("claimer", claimer);
        }

        // 分页查询
        Page<ClaimRecord> pageResult = claimRecordService.page(new Page<>(page, size), wrapper);
        
        // 关联查询失物信息
        for (ClaimRecord record : pageResult.getRecords()) {
            LostItem lostItem = lostItemService.getById(record.getItemId());
            if (lostItem != null) {
                record.setItemTitle(lostItem.getTitle());
                record.setItemCategory(lostItem.getCategory());
                record.setItemLocation(lostItem.getLocation());
            }
        }
        
        model.addAttribute("page", pageResult);
        model.addAttribute("claimer", claimer);
        
        return "claim-record/list";
    }

    /**
     * 认领物品页面
     */
    @GetMapping("/claim/{itemId}")
    public String claimPage(@PathVariable Long itemId, Model model, HttpSession session) {
        // 检查登录状态
        if (session.getAttribute("admin") == null) {
            return "redirect:/login";
        }

        LostItem lostItem = lostItemService.getById(itemId);
        if (lostItem == null || lostItem.getStatus() == 1) {
            model.addAttribute("error", "物品不存在或已被认领");
            return "redirect:/lost-item/list";
        }

        model.addAttribute("lostItem", lostItem);
        return "claim-record/claim";
    }

    /**
     * 执行认领操作（事务 + 乐观锁）
     */
    @PostMapping("/claim")
    public String claim(@RequestParam Long itemId,
                        @RequestParam String claimer,
                        @RequestParam String contact,
                        Model model, HttpSession session) {
        // 检查登录状态
        if (session.getAttribute("admin") == null) {
            return "redirect:/login";
        }

        // 验证联系方式
        if (!StringUtils.hasText(contact)) {
            model.addAttribute("error", "联系方式不能为空");
            return "redirect:/claim-record/claim/" + itemId;
        }

        try {
            boolean success = claimRecordService.claimItem(itemId, claimer, contact);
            if (success) {
                model.addAttribute("message", "认领成功");
            } else {
                model.addAttribute("error", "认领失败，请重试");
            }
        } catch (Exception e) {
            model.addAttribute("error", e.getMessage());
        }

        return "redirect:/lost-item/list";
    }

    /**
     * 查看认领记录详情
     */
    @GetMapping("/detail/{id}")
    public String detail(@PathVariable Long id, Model model, HttpSession session) {
        // 检查登录状态
        if (session.getAttribute("admin") == null) {
            return "redirect:/login";
        }

        ClaimRecord claimRecord = claimRecordService.getById(id);
        if (claimRecord != null) {
            LostItem lostItem = lostItemService.getById(claimRecord.getItemId());
            if (lostItem != null) {
                claimRecord.setItemTitle(lostItem.getTitle());
                claimRecord.setItemCategory(lostItem.getCategory());
                claimRecord.setItemLocation(lostItem.getLocation());
                claimRecord.setItemDescription(lostItem.getDescription());
                claimRecord.setItemLostTime(lostItem.getSubmitTime());
            }
        }
        
        model.addAttribute("claimRecord", claimRecord);
        return "claim-record/detail";
    }
}